﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.ComponentModel;

namespace sgsBase
{
	public partial class SgsPage : System.Web.UI.Page
	{
		private SgsGlobal _gl;

		protected string ReturnPage = "";
		protected string Javascript = "";

		public SgsGlobal Gl
		{
			get
			{
				if (_gl == null)
					_gl = (SgsGlobal)HttpContext.Current.ApplicationInstance;
				return _gl;
			}
			set
			{
				_gl = value;
			}
		}

        protected string CheckFormvar(string name, string def)
        {
            if (Request[name] != null)
            {
                if (Request[name].ToString() == "")
                    return def;
                return Request[name].ToString();
            }
                
            return def;
        }
		protected string CheckFormvar(string name)
		{
			return CheckFormvar(name, "");
		}

		protected string encode(object val)
		{
			return encode(val.ToString());
		}
		protected string encode(string val)
		{
			val = Server.UrlEncode(val);
			val = val.Replace("'", "%27");
			val = val.Replace("\"", "%22");
			val = val.Replace("&", "%26");
			return val;
		}

		protected void Page_PreInit(object sender, EventArgs e)
		{
			if (this.MasterPageFile == null)
				return;
			if (CheckFormvar("Lite") == "1")
				SessionSet("Lite", "1");
			else if (CheckFormvar("Lite") == "0")
				SessionSet("Lite", "0");

			if (SessionCheck("Lite", "0") == "1")
			{
				this.MasterPageFile = "~/MasterFiles/lite.Master";
				return;
			}
			if (CheckFormvar("Print") == "1")
				this.MasterPageFile = "~/MasterFiles/Print.Master";
		}
		protected void Page_Load(object sender, EventArgs e)
		{
            Gl = (SgsGlobal)HttpContext.Current.ApplicationInstance;

			if (Request["ReturnPage"] != null)
				ReturnPage = Request["ReturnPage"].ToString();

			PageLoad(sender, e);
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (Gl == null)
			    Gl = (SgsGlobal)HttpContext.Current.ApplicationInstance;
			Control[] ctlList = FlattenHierarchy(this);
			foreach (Control ctl in ctlList)
			{
				WebControl wctl = ctl as WebControl;

				//standard check of all web controls
				if (wctl != null)
				{
					WebControlCheck(wctl);
				}
				else
				{
					// if it is a user control, we need to check it on two levels:
					// 1. does the control as a whole have security? if so, check it.
					// 2. do pieces inside the control have security? if so, check them as well. 
					UserControl uctl = ctl as UserControl;

					if (uctl != null)
					{
						if (uctl.Attributes["sgsSecurity"] != null)
						{
							SecLevel seclvl = Gl.CurUser.Security.GetPermission(uctl.Attributes["sgsSecurity"]);
							if (seclvl == SecLevel.Hidden)
								uctl.Visible = false;
//							else if (seclvl == SecLevel.Visible)
//								uctl.Enabled = false;							
						}
						if (uctl.ToString() != "ASP.masterfiles_site_master")
						{
							Control[] subList = FlattenHierarchy(uctl);
							foreach (Control sctl in subList)
							{
								wctl = sctl as WebControl;

								if (wctl != null)
								{
									WebControlCheck(wctl);
								}
								else
								{
									HtmlControl htcl = sctl as HtmlControl;
									
									if (htcl != null)
									{
										if (htcl.TagName == "div")
										{
											ControlCheck(htcl);
										}
									}
								}
							}
						}
					}
				}
			}
			PagePreRender(sender, e);
			//if (Javascript != "")
			//	((SiteMasterPage)Master).SetOnLoad(Javascript);
		}

		private void WebControlCheck(WebControl wctl)
		{
			if (wctl.Attributes["sgsSecurity"] != null)
			{
				SecLevel seclvl = Gl.CurUser.Security.GetPermission(wctl.Attributes["sgsSecurity"]);
				if (seclvl == SecLevel.Hidden)
					wctl.Visible = false;
				else if (seclvl == SecLevel.Visible)
					wctl.Enabled = false;
			}
		}

		private void ControlCheck(HtmlControl wctl)
		{
			if (wctl.Attributes["sgsSecurity"] != null)
			{
				SecLevel seclvl = Gl.CurUser.Security.GetPermission(wctl.Attributes["sgsSecurity"]);
				if (seclvl == SecLevel.Hidden || seclvl == SecLevel.Visible)
					wctl.Visible = false;
			}
		}

		/// <summary>
		/// Return to whatever page is specified in ReturnPage
		/// </summary>
		protected void ReturnToCaller()
		{
			Response.Redirect(ReturnPage);
		}

		private void SetControl()
		{

		}
		protected static Control[] FlattenHierarchy(Control root)
		{
			List<Control> list = new List<Control>();
			list.Add(root);
			if (root.HasControls())
			{
				foreach (Control control in root.Controls)
				{
					list.AddRange(FlattenHierarchy(control));
				}
			}
			return list.ToArray();
		}

		protected virtual void PageLoad(object sender, EventArgs e)
		{
		}

		protected virtual void PagePreRender(object sender, EventArgs e)
		{
		}

		public void AddMessage(string text)
		{
			if (text == "")
				return;
			Gl.Message += text + "<br>";
		}
		public void AddMessage(string text, string redirect)
		{
			Gl.Message += text + "<br>";
			Response.Redirect(redirect);
		}
		public void ClearMessage()
		{
			Gl.Message = "";
		}
		/// <summary>
        /// Initializes or returns Session variable. 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="classtype"></param>
        /// <param name="inclass"></param>
        public object SessionInit(string name, Type classtype, object inclass)
        {
            if (inclass != null)
                return inclass;

            return SessionInit(name, classtype);
        }
        public object SessionInit(string name, Type classtype)
        {
            object inclass;
            if (Session[name] != null)
            {
                inclass = Session[name];
                return inclass;
            }

            inclass = Activator.CreateInstance(classtype);
            Session[name] = inclass;
            return inclass;
        }

		public void SessionSet(string name, object val)
		{
			Session[name] = val.ToString();
		}

		public string SessionCheck(string name, string def="")
		{
			if (Session[name] == null)
				return def;

			return Session[name].ToString();
		}

        public void SessionClear(string name)
        {
            Session[name] = null;
        }

		protected string Money(string inp)
		{
			return HTMLHelper.Money(inp);
		}
		protected string Money(object inp)
		{
			return HTMLHelper.Money(inp);
		}
		protected string Money(object inp, bool ZeroAsBlank)
		{
			return HTMLHelper.Money(inp, ZeroAsBlank);
		}

		protected string Date(object inp)
		{
			return HTMLHelper.Date(inp);
		}

		//protected string BrVersion(object inp)
		//{
		//    if (gl.OlderBrowser)
		//        return "";

		//    return inp.ToString();
		//}
		//protected string BrowserVersion(object inpNew, object inpOld)
		//{
		//    if (gl.OlderBrowser)
		//        return inpOld.ToString(); ;

		//    return inpNew.ToString();
		//}

		protected bool isPrinting()
		{
			return (CheckFormvar("Print", "") == "1");
		}

	}

}
